package com.zh.note.huawei.onehundred.阿里巴巴找黄金宝箱3;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * https://dream.blog.csdn.net/article/details/130962395
 */
public class Main {
    public static void main(String[] args) {
        // Scanner sc = new Scanner(System.in);
        // String inputStr = sc.nextLine();
        // int target = sc.nextInt();
        String inputStr = "6,3,1,6";
        int target = 3;
        // String inputStr = "5,6,7,5,6,7";
        // int target = 2;
        String[] split = inputStr.split(",");
        int[] nums = Arrays.stream(split).mapToInt(Integer::parseInt).toArray();
        solution2(nums, target);
    }

    private static void solution2(int[] nums, int target) {
        // key是数组值，value是下标
        Map<Integer, Integer> lastIndexMap = new HashMap<>();
        int res = -1;
        for (int i = 0; i < nums.length; i++) {
            int currentNum = nums[i];
            if (lastIndexMap.containsKey(currentNum) && i - lastIndexMap.get(currentNum) <= target) {
                res = lastIndexMap.get(currentNum);
                break;
            }
            lastIndexMap.put(currentNum, i);
        }
        System.out.println(res);
    }

    private static void solution(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            int j = nums.length - 1;
            while (nums[i] != nums[j]) {
                j--;
            }
            if (i < j && (j - i) <= target) {
                System.out.println(i);
                return;
            }
        }
        System.out.println(-1);

    }
}
